package com.blog.serviceImpl;

import com.blog.dao.UserDao;
import com.blog.entity.User;
import com.blog.enums.StaticVariable;
import com.blog.service.UserService;
import com.blog.util.MD5Utils;
import com.blog.util.MailUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务层接口实现类
 * Securityr认证：实现UserDetailsService
 *
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User checkUser(String username, String password) {
        User user = userDao.findByUsernameAndPassword(username, MD5Utils.code(password));
        return user;
    }

    @Override
    public User checkUserByEmailAndPassword(String email, String password) {
        //邮箱盐值
        String emailKey = email.substring(0,email.lastIndexOf("@"));
        return userDao.selectByEmailAndPassword(email,MD5Utils.code(password+emailKey));
    }

    @Override
    public int checkEmailCode(String email) {
        //Math.random生成一个[0.0，1.0）之间的小数,乘以1000000将范围转为[10000,999999]
        int code = (int) (Math.random() * 1000000);

        try {
            //先将邮件验证码放于redis并设置过期时间为5分钟
            String redisMailKey = email.substring(0, email.lastIndexOf("@"));
            ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
            Integer val = operations.get(redisMailKey);
            if (val == null) {
                operations.set(redisMailKey, code, 5, TimeUnit.MINUTES);
                //再发送邮件
                MailUtil.textMail("SUOYUE | 验证邮箱", "你好：" + email + "\n你的验证码为：" + code + "\n请注意：验证5分钟内有效", email);
                return 1;
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int checkSignInInfo(User user,String code) {
        String email = user.getEmail();

        //判断密码输入是否正确
        if(!user.getPassword().equals(user.getConfirmPassword())){
            return 2;
        }

        //将邮件验证码放于redis并设置过期时间为5分钟
        String redisMailKey = email.substring(0,email.lastIndexOf("@"));
        ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
        Integer val = operations.get(redisMailKey);
        //redis是否可以查找到邮箱对应的有效验证码
        if(val == null){
            return 3;
        }else if(!code.equals(Integer.toString(val))){
            //判断验证码是否有效
            return 4;
        }else {
            //注册成功,先判断邮箱是否已注册
            User userInfo = userDao.selectUserByEmail(email);
            if(userInfo != null){
                return 5;
            }
            //插入用户,插入之前先对密码进行加密(MD5加密＋盐值：邮箱)
            user.setPassword(MD5Utils.code(user.getPassword()+redisMailKey));
            //初始化用户可用
            user.setEnabled(true);
            user.setRecommend(false);
            user.setType(StaticVariable.userType);
            user.setAvatar(StaticVariable.avatarImg);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            if(StringUtils.isEmpty(user.getUsername())){
                user.setUsername(email);
            }
            //插入用户信息
            int resUser = userDao.insertUserInfo(user);
            //配置用户的角色，默认都是普通用户
//            String[] roles = new String[]{"2"};
//            int resRole = userDao.addRoles(roles,user.getId());
//            boolean b = (resUser == 1) && (resRole == roles.length);
            if (resUser == 1) {
                return 1;
            } else {
                return 8;
            }
        }

    }

    @Override
    public int checkEmailAndCode(String email, String code) {
        //redis获取登录验证码并校样
        String redisMailKey = email.substring(0,email.lastIndexOf("@"));
        ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
        Integer val = operations.get(redisMailKey);
        if(code.equals(Integer.toString(val))){
            return 1;
        }
        return 0;
    }

    @Override
    public User selectUserByEmail(String email) {
        return userDao.selectUserByEmail(email);
    }

    @Override
    public int updateUserInfo(User user) {
        return userDao.updateUserInfo(user);
    }

    @Override
    public List<User> selectUserInfo() {
        return userDao.selectUserInfo();
    }

    @Override
    public List<User> selectFirstPageUser() {
        return userDao.selectFirstPageUser();
    }

    @Override
    public List<User> selectUserList() {
        return userDao.selectUserList();
    }

    @Override
    public User selectUserDetailInfo(Long id) {
        return userDao.selectUserDetailInfo(id);
    }

    @Override
    public List<User> selectDynamicUserInfo(User user) {
        return userDao.selectDynamicUserInfo(user);
    }

    @Override
    public List<User> selectBooleanUserInfo(User user) {
        return userDao.selectBooleanUserInfo(user);
    }

    /**
     * Securityr认证：实现UserDetailsService,重写loadUserByUsername,
     * 登录校样：只传递账号，验证用户是否存在，密码交由Security验证，无需处理
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
//    @Override
//    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        User user = userDao.selectUserByEmail(s);
//        if(user == null){
//            //避免返回null，这里返回一个不含有任何值的User对象，在后期的密码比对过程中一样会验证失败
//            return new User();
//        }
//
//        //存一份于session中
//        HttpSession session = null;
//        session.setAttribute("user",user);
//
//        //查询用户的角色信息，并返回存入user中
//        List<Role> roles = userDao.getRolesByUid(user.getId());
//        user.setRoles(roles);
//        return user;
//    }

}
